﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Text;
using System.IO;

using DataAccess;

namespace it.senquocte.com.Control.Captcha
{
    public partial class Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Clear();
            int height = 40;
            int width = 110;
            Bitmap bmp = new Bitmap(width, height);

            RectangleF rectf = new RectangleF(10, 5, 0, 0);

            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.LightGray);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            string captcha = this.RandomSring();
            Session["captcha"] = captcha;

            HttpCookie ck = new HttpCookie("Captcha");
            ck.Value = captcha;
            Response.Cookies.Add(ck);

            g.DrawString(captcha, new Font("Thaoma", 18, FontStyle.Italic), Brushes.Teal, rectf);
            //g.DrawRectangle(new Pen(Color.Red), 1, 1, width - 2, height - 2);
            g.Flush();
            Response.ContentType = "image/jpeg;base64";
            bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
            g.Dispose();
            bmp.Dispose();
        }
        private string RandomSring()
        {
            byte leght = 5;
            string[] fontsArray = { "Arial Black", "Lucida Sans Unicode", "Time New Roman" };
            string characterArray = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            Random rand = new Random();
            StringBuilder strCaptcha = new StringBuilder();
            for (int i = 0; i < leght; i++)
            {
                string str = characterArray[rand.Next(characterArray.Length)].ToString();
                strCaptcha.Append(str);
            }
            return strCaptcha.ToString();
        }

    }
}